package com.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.UnknownHostException;
public class Server {
	public static void main(String[] args) {
		BufferedReader br;
		PrintWriter pw;
		Socket socket;
		ServerSocket serversocket;
		String data = "";
		Character ch;
		try {			
			System.out.println("Server start");
			serversocket = new ServerSocket(1002);
			socket = new Socket();			
			socket = serversocket.accept(); //cho*` fia' Client ket noi'
			br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			pw = new PrintWriter(socket.getOutputStream(), true);			
			while (true) {
				data = br.readLine(); //?! cho*` cho de'n luc nao` du~ lieu to*i' thi bdau doc., neu chua co du~ lieu gui den' -> tiep tuc cho`
				System.out.println("Math expression received from Client: " + data); 
				//xu ly
				ch = data.charAt(0);
				int a = Integer.parseInt(ch.toString());
				ch = data.charAt(2);
				int b = Integer.parseInt(ch.toString());
				switch (data.charAt(1)) {
					case '+':
						pw.println(a+b);
						break;
					case '-':
						pw.println(a-b);
						break;
					case '*':
						pw.println(a*b);
						break;
					case '/':
						pw.println(a/b);
						break;
					default:
						pw.println("No result");
						break;
				}
				
				System.out.println("Connection..");
			}			
		} catch(UnknownHostException unknHostE) {
			unknHostE.printStackTrace();
		} catch(IOException ioE) {
			ioE.printStackTrace();
		}
	}	
}